package com.bac.rentmap.ad.flat.crawler.localaddress;

import java.util.List;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.util.StringUtils;

import com.bac.rentmap.ad.flat.LocalAddress;
import com.bac.rentmap.ad.flat.LocalAddressPrefix;

public class StreetOnlyLocalAddressParser implements LocalAddressParser {
	private static final Logger log = Logger
			.getLogger(SimpleLocaAddressParser.class.getName());

	private Pattern addressPattern;

	public StreetOnlyLocalAddressParser() {
		List<String> prefixes = LocalAddressPrefix.getSynonymPatterns();
		String prefixesRegex = StringUtils.collectionToDelimitedString(
				prefixes, "|");
		addressPattern = Pattern.compile("\\s*(" + prefixesRegex
				+ ")?\\.?\\s*([\\p{L}\\d][\\.\\p{L}\\s\\-]*\\p{L})");
		log.info("Pattern: " + addressPattern);
	}

	public LocalAddress parse(String string) {
		string = string + " ";
		LocalAddressPrefix prefix = null;
		String street = null;
		Matcher matcher = addressPattern.matcher(string);
		boolean matchFound = matcher.find();
		if (matchFound) {
			street = matcher.group(2);
			String prefixString = matcher.group(1);
			if (prefixString != null) {
				prefix = LocalAddressPrefix.valueOfSynonym(prefixString);
			}
		} else {
			street = string;
		}
		LocalAddress res = new LocalAddress(prefix, street, null);
		log.info("Parsed '" + string + "' to " + res);
		return res;
	}
}
